# coding: utf8
"""通用函数文件"""
import os
import platform
import msvcrt
import sys
from prpcrypt import Prpcrypt

def toGbkText(text):
	if isinstance(text, unicode):
		return text.encode('gbk')
	else:
		try:
			return unicode(text, 'utf-8').encode('gbk')
		except:
			return text

def toUtf8Text(text):
	if isinstance(text, unicode):
		return text.encode('utf-8')
	else:
		try:
			return unicode(text, 'gbk').encode('utf-8')
		except:
			return text

def getFiles(dirPath):
	for root, dirs, files in os.walk(dirPath):
		return files
	else:
		return []

def getSetCookies(url, headers=None, timeout=10, verify=True):
	agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36'
	try:
		if headers:
			keys = [k.lower() for k in headers.keys()]
			if 'user-agent' in keys:
				for k in headers.keys():
					if k.lower() == 'user-agent':
						headers[k] = agent
			else:
				headers['user-agent'] = agent
		else:
			headers = {'user-agent':agent}
		session = requests.Session()
		session.get(url, headers=headers, timeout=timeout, verify=verify)
		return session.cookies
	except Exception as e:
		return {}

def get_url(url, headers=None, timeout=30, verify=True):
	agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36'
	try:
		if headers:
			keys = [k.lower() for k in headers.keys()]
			if 'user-agent' in keys:
				for k in headers.keys():
					if k.lower() == 'user-agent':
						headers[k] = agent
			else:
				headers['user-agent'] = agent
		else:
			headers = {'user-agent':agent}
		r = requests.get(url, headers=headers, timeout=timeout, verify=verify)
		return r.content
	except Exception as e:
		return

def ReadFile(filePath,encoding="utf-8"):
	with codecs.open(filePath,"r",encoding) as f:
		return f.read()

def WriteFile(filePath,u,encoding="gbk"):
	with codecs.open(filePath,"wb") as f:
		f.write(u.encode(encoding,errors="ignore"))

def UTF8_2_GBK(src,dst):
	content = ReadFile(src,encoding="utf-8")
	WriteFile(dst,content,encoding="gbk")
	
def convert_2_str(text, encoding='utf8'):
	if isinstance(text, unicode):
		return text.encode(encoding)
	elif isinstance(text, (float, int)):
		return str(text)

def decrypt(text):
	"""解码"""
	p = Prpcrypt()
	return P.decrypt(text)

def strip_bom(fn='conf.cfg'):
	"""清除utf8 with BOM 的前3个字符"""
	with open(fn) as f:
		content = f.read()

	if content[:3] == '\xEF\xBB\xBF':
		with open(fn, 'wb') as f:
			f.write(content[3:])

def sys_to_gbk(val, sys_type='Test'):
	"""打印带有系统前缀"""
	return to_gbk(val)

def sys_to_utf8(val, sys_type='Test'):
	"""打印带有系统前缀"""
	return to_utf8(val)

def to_gbk(val):
	"""返回gbk"""
	if isinstance(val, unicode):
		val = val.encode('utf8')
	return unicode(val, 'utf-8').encode('gbk')

def to_utf8(val):
	"""返回utf8"""
	if isinstance(val, unicode):
		val = val.encode('utf8')
	return unicode(val, 'utf-8').encode('utf-8')

def sys_encode(text, txt='Hello'):
	"""输入文本"""
	if platform.system() == 'Windows':
		return sys_to_gbk(text, txt)
	else:
		return sys_to_utf8(text, txt)


def try_except_funcs(logging):
	def _in_try_except_funcs(funcs):
		def __in_try_except_funcs(instance):
			try:
				funcs(instance)
			except Exception as e:
				logging.info(sys_to_utf8(e, instance.__class__))
		return __in_try_except_funcs
	return _in_try_except_funcs


def del_file(logging, file_name):
	"""删除文件"""
	if os.path.exists(file_name):
		os.remove(file_name)
		try:
			file_name = unicode(file_name, 'gbk').encode('utf-8')
		except:
			pass
		logging.info(sys_encode('删除%s文件成功...' % file_name))
		

def is_valid_date(str):
	'''判断是否是一个有效的日期字符串'''
	try:
		time.strptime(str, "%Y-%m-%d")
		return True
	except:
		return False


def write_txt(item, file='data_test.txt'):
	"""写入txt"""
	with open(file, 'ab') as f:
		f.write(item)


def write_json(file, item):
	"""写入json"""
	import codecs
	import json
	f = codecs.open(file, mode='ab', encoding='utf-8')
	line = json.dumps(item) + '\n'
	f.write(line.decode("unicode_escape"))
	f.close()


def set_env_path(file_path):
	"""设置环境变量"""
	path = os.environ['path']
	old_file = 'old_path_environ.txt'

	if not os.path.exists(old_file):
		with open(old_file, 'w') as f:
			f.write('旧的环境变量:\n'+path)
			
	os.environ['path'] = abs_path+ ';' + path
	pass
	

def get_abs_dirname(file_name, cond='.'):
	"""获取父级目录, 或者父父级目录绝对路径

	cond='.' 代表父 '..'代表父父 """
	return os.path.abspath(os.path.dirname(file_name)+os.path.sep+cond) 
	

def create_dir(folders):
	"""创建目录"""
	if not isinstance(folders, list):
		raise TypeError('Argument must be list')
	for fn in folders:
		if not os.path.exists(fn):
			os.makedirs(fn)


def get_logging(logging, **kwags):
	"""格式化输出日志信息
	
	必选参数有
	:param logging: logging

	可以选择的参数有
	:param logging_file: 	日志文件路径
	:param mode: 			写入文件模式
	:param asctime: 		输出带时间日志
	:param levelname: 		输出带日志等级
	
	:return : logging
	"""
	level_dict = {
		'notset': 0,
		'debug': 10,
		'info': 20,
		'warning': 30,
		'error': 40,
		'critical': 50,
	}
	logging_file 	= kwags.get('logging_file', None)
	mode 			= kwags.get('mode', 'a')
	asctime 		= kwags.get('asctime', False)
	levelname 		= kwags.get('levelname', False)
	level 			= kwags.get('level', 'info')
	console 		= kwags.get('console', False)

	format_ = '[PID: %(process)d] [path: %(pathname)s] [line: %(lineno)d] %(message)s'
	format_ = ('[%(levelname)s] ' + format_) if levelname else format_
	format_ = ('[%(asctime)s] ' + format_) if asctime else format_

	logging.basicConfig(
		level=level_dict.get(level, 20),
		format=format_,
		datefmt='%Y-%m-%d %H:%M:%S',
		filename=logging_file,
		filemode=mode,
		encoding=kwags.get('encoding', 'utf8')
		)

	if console:
		console = logging.StreamHandler()
		console.setLevel(logging.INFO)
		formatter = logging.Formatter(format_)
		console.setFormatter(formatter)
		logging.getLogger('').addHandler(console)

	return logging

def num_2_bin(num):
	"""十进制数转2进制数"""
	la = []
	if num < 0:
		return '-' + my_bin(abs(num))
	while True:
		num, remainder = divmod(num, 2)
		la.append(str(remainder))
		print (la)
		if num == 0:
			return ''.join(la[::-1])

def is_chinese(uchar):
	"""判断一个unicode是否是汉字"""
	if u'\u4e00' <= uchar <= u'\u9fa5':
		return True
	else:
		return False

def to_gbk(val):
	"""返回gbk"""
	if isinstance(val, unicode):
		val = val.encode('utf8')
	return unicode(val, 'utf-8').encode('gbk')

def pwd_input():
	"""输入内容变成星号"""  
	chars = []   
	while True:  
		try:  
			newChar = msvcrt.getch().decode(encoding="utf-8")  
		except:  
			return input("你很可能不是在cmd命令行下运行，密码输入将不能隐藏:")  
		if newChar in '\r\n': # 如果是换行，则输入结束               
			 break   
		elif newChar == '\b': # 如果是退格，则删除密码末尾一位并且删除一个星号   
			 if chars:    
				 del chars[-1]   
				 msvcrt.putch('\b'.encode(encoding='utf-8')) # 光标回退一格  
				 msvcrt.putch( ' '.encode(encoding='utf-8')) # 输出一个空格覆盖原来的星号  
				 msvcrt.putch('\b'.encode(encoding='utf-8')) # 光标回退一格准备接受新的输入                   
		else:  
			chars.append(newChar)  
			msvcrt.putch('*'.encode(encoding='utf-8')) # 显示为星号  
	return (''.join(chars) )

def clear_screen(typ=None):
	"""
	清除屏幕信息
	"""
	if typ:
		if time.strftime("%H:%M") in ["20:%s" % i for i in range(59)]:
			os.system('cls' if platform.system() == 'Windows' else 'clear')
	else:
		os.system('cls' if platform.system() == 'Windows' else 'clear')

def get_space_num(v, num=20):
	"""
	获取空格数量
	"""
	space_num = 10
	len_v = len(v)
	
	if isinstance(v, unicode):
		len_v += 2
	if len_v < num:
		space_num = num - len_v
	return space_num

def pick_str(str_,  bs,  es='"'):
	"""
	Function doc
	切割字符串, 从bs开始切割, 到es结束
	"""
	bs_len = len(bs)    	# 长度
	a = str_.find(bs)    	# 位置

	if a != -1:
		if es:
			b = str_.find(es, a+bs_len)  			# 从 str_ 的 bs 之后开始查找 es
			if b != -1: 							# es 的位置
				return str_[a+bs_len:b].strip()  	# str切片取 bs之后 到es 之间的字符串
		else:
			return str_[a+bs_len:].strip()
	return ''

def travelTree(currentPath, count=4, folder_name=None):
	"""生成文件目录结构"""
	if not os.path.exists(currentPath):
		return
	if os.path.isfile(currentPath):
		if not currentPath.endswith('.pyc'):
			fileName = os.path.basename(currentPath)
			print '\t' * count + '├─ ' + fileName
	elif os.path.isdir(currentPath):
		if folder_name:
			print '\t' * count + '├─ ' + folder_name + ' (folder)'
		else:
			print '\t' * count + '├─ ' + currentPath + ' (folder)'
		pathList = os.listdir(currentPath)
		for folder_name in pathList:
			if '.git' in folder_name:
				continue
			travelTree(currentPath + '/' + folder_name, count + 1, folder_name)

	# travelTree('E:/linux_project', 1)

def mouse_absolute(x, y, x2, y2):
	"""
	控制鼠标点击滑块移动
	"""
	from ctypes import windll
	import win32api
	import win32con
	windll.user32.SetCursorPos(x, y)    #鼠标移动到  
	win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)    #左键按下
	time.sleep(0.2)
	mw = int(x2 * 65535 / SW) 
	mh = int(y2 * 65535 / SH)
	win32api.mouse_event(win32con.MOUSEEVENTF_ABSOLUTE + win32con.MOUSEEVENTF_MOVE, mw, mh, 0, 0)
	time.sleep(0.2)
	win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)


def mouse_move(x, y):
	""" 控制鼠标移动 """
	import win32api
	import win32con
	from ctypes import windll
	t = 0
	while t < 1:
		t += 1
		windll.user32.SetCursorPos(x, y)    #鼠标移动到
		num = 0
		while num < 100:
			num += 1
			if num < 25:
				x += 1
				y += 1
			elif num > 25 and num < 50:
				x -= 1
				y += 1
			elif num > 50 and num < 75:
				x -= 1
				y -= 1
			else:
				x += 1
				y -= 1
			mw = int(x * 65535 / SW) 
			mh = int(y * 65535 / SH)
			time.sleep(0.02)
			win32api.mouse_event(win32con.MOUSEEVENTF_ABSOLUTE + win32con.MOUSEEVENTF_MOVE, mw, mh, 0, 0)
			pass